package cn.hr.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hr.pojo.Archives;
import cn.hr.pojo.SalaryPro;
import cn.hr.pojo.SysUser;
import cn.hr.pojo.Wor;
import cn.hr.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hr.service.WorService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 试题控制器
 * @author MO
 *
 */
@Controller
@RequestMapping("/sys/wor")
public class WorController {
	private Logger logger = LoggerFactory.getLogger(WorController.class);
	@Resource
	private WorService worService;

	private String meagess;

	/**
	 * 查询
	 * @return
	 */
	@RequestMapping("/showList")
	public String showList(@RequestParam(value = "pageIndex",required = false)String pageIndex,
						   @RequestParam(value = "worType",required = false)String worType,
						   @RequestParam(value = "oId",required = false)String oId,
						   @RequestParam(value="isStart",required = false)String isStart,
						   @RequestParam(value="title",required = false)String title,
						   Model model){
		Map<String,Object> map = new HashMap<>();
		int index = 1;
		if (pageIndex!=null&&pageIndex!=""){
			index = Integer.parseInt(pageIndex);
		}
		if (title!=null&&title!=""){
			map.put("title",title);
			model.addAttribute("title",title);
		}
		if (worType!=null&&worType!=""){
			map.put("worType",Integer.parseInt(worType));
			model.addAttribute("worType",worType);
		}
		if (oId!=null&&oId!=""){
			map.put("oId",Integer.parseInt(oId));
			model.addAttribute("oId",oId);
		}
		if (isStart!=null&&isStart!=""){
			map.put("isStart",Integer.parseInt(isStart));
			model.addAttribute("isStart",isStart);
		}
		try {
			PageInfo<Map> pageInfo = worService.findListByCondition(map,index);
			model.addAttribute("pageInfo",pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wor/showList";
	}

	@RequestMapping("/list")
	public String list(){
		return "wor/worList";
	}

	/**
	 * 跳转到添加页面
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Model model){
		Wor wor = new Wor();
		wor.setIsStart(0);
		model.addAttribute("wor",wor);
		model.addAttribute("attr","add");
		return "wor/AU";
	}

	/**
	 * 添加
	 * @param session
	 * @return
	 */
	@RequestMapping("/addSave")
	public String addSave(Wor wor, HttpSession session, @RequestParam(value = "attach", required = false) MultipartFile attach) {
		String accessory = null;
		boolean flag = true;
		String path = "D:/wor" + File.separator + "static" + File.separator + "upload";
		try {
			if (!attach.isEmpty()) {
				String oldFileName = attach.getOriginalFilename();//获取原文件名
				String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
				int fileSize = 900000000;
				if (attach.getSize() > fileSize) {
					flag = false;
				} else if (prefix.equalsIgnoreCase("txt") || prefix.equalsIgnoreCase("doc")) {
					String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "wor." + prefix;
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.getParentFile().mkdir();
						targetFile.createNewFile();
					}
					attach.transferTo(targetFile);
					accessory = path + File.separator + fileName;
				} else {
					flag = false;
				}
			}
			if (flag) {
				wor.setAccessory(accessory);
				wor.setCreatedById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
				wor.setCreatedDate(new Date());
				if (wor.getIsStart()==null){
					wor.setIsStart(0);
				}
				if (worService.insert(wor)) {
					meagess = "redirect:/sys/wor/list";
				}else{
					meagess = "redirect:/sys/wor/add";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return meagess;
	}

	/**
	 * 跳转到修改页面
	 * @param _id
	 * @param model
	 * @return
	 */
	@RequestMapping("/update")
	public String update(@RequestParam(value="id")String _id, Model model){
		Wor wor = null;
		try {
			wor = worService.get(Integer.parseInt(_id));
			model.addAttribute("attr","update");
			model.addAttribute("wor",wor);
			model.addAttribute("oId",wor.getoId());
			model.addAttribute("worType",wor.getWorType());
			model.addAttribute("rank",wor.getWorRank());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  "wor/AU";
	}

	/**
	 * 添加
	 * @param session
	 * @return
	 */
	@RequestMapping("/updateSave")
	public String updateSave(Wor wor, HttpSession session, @RequestParam(value = "attach", required = false) MultipartFile attach){
		String accessory = null;
		boolean flag = true;
		String path = "D:/wor" + File.separator + "static" + File.separator + "upload";
		try {
			if (!attach.isEmpty()) {
				String oldFileName = attach.getOriginalFilename();//获取原文件名
				String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
				int fileSize = 900000000;
				if (attach.getSize() > fileSize) {
					flag = false;
				} else if (prefix.equalsIgnoreCase("txt") || prefix.equalsIgnoreCase("doc")) {
					String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "wor." + prefix;
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.getParentFile().mkdir();
						targetFile.createNewFile();
					}
					attach.transferTo(targetFile);
					accessory = path + File.separator + fileName;
				} else {
					flag = false;
				}
			}
			if (flag) {
				wor.setAccessory(accessory);
				wor.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
				wor.setModifyDate(new Date());
				if (wor.getIsStart()==null){
					wor.setIsStart(0);
				}
				if (worService.update(wor)) {
					meagess = "redirect:list";
				}else{
					meagess = "redirect:/update?id="+wor.getId().toString();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return meagess;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam(value = "id")String id){
		try {
			meagess = "false";
			if (worService.delete(Integer.parseInt(id))) {
				meagess = "true";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  meagess;
	}


	@RequestMapping("/delFile")
	@ResponseBody
	//删除文件并且把字段改成空
	public String delFile(@RequestParam("id")String id) {
		try {
			Wor wor = worService.get(Integer.parseInt(id));
			meagess = "false";
			if (worService.updateByNull(Integer.parseInt(id))){
				File file = new File(wor.getAccessory());
				if (file.exists()) {
					file.delete();
					meagess = "true";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return meagess;
	}

	//文件下载相关代码
	@RequestMapping("/downloadFile")
	public String downloadFile(@RequestParam("id") Integer id, HttpServletResponse response) {
		Wor wor = null;
		String fileName = null;
		try {
			wor = worService.get(id);
			fileName = wor.getTitle() + ".zip";
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (fileName != null) {
			File file = new File(wor.getAccessory());
			if (file.exists()) {
				response.setContentType("application/force-download");
				try {
					response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));//设置下载文件名
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("ok");
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
}
